<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { ElLink, ElMessage, ElSpace, ElButton, ElMessageBox, ElTag } from 'element-plus'
import { Table, TableColumn } from '@/components/Table'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { useRouter } from 'vue-router'
import TaskDialog from './components/TaskDialog.vue'
import { SUCCESS_CODE } from '@/constants'
import { taskResourceApi, deleteTaskApi } from '@/api/task'

const { t } = useI18n()

const operateType = ref('add')
const rowId = ref('')

const searchParams = ref({})

const emit = defineEmits(['changeComponent'])

const { currentRoute } = useRouter()

const getColumns = () => {
  const columns = [
    { field: 'name', label: '名称' },
    { field: 'describe', label: '描述' },
    {
      field: 'status',
      label: '状态',
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              <ElTag type={row.status === '0' ? 'success' : 'danger'}>
                {row.status === '0' ? '启用' : '禁用'}
              </ElTag>
            </>
          )
        }
      }
    },
    {
      field: 'create_time',
      label: '创建时间'
    },
    {
      field: 'deadline',
      label: '过期时间'
    },
    {
      field: 'action',
      label: '操作',
      fixed: 'right',
      minWidth: 80,
      slots: {
        default: (data) => {
          const row = data.row
          return (
            <>
              <ElSpace>
                <ElLink
                  class="mr-1"
                  type="primary"
                  underline={false}
                  disabled={row.status === 'forbid'}
                  onClick={() => handleEdit(row.id)}
                >
                  编辑
                </ElLink>
                <ElLink type="primary" underline={false} onClick={() => handleDelete(row)}>
                  删除
                </ElLink>
              </ElSpace>
            </>
          )
        }
      }
    }
  ]
  return columns
}
const columns = reactive<TableColumn[]>(getColumns() as TableColumn[])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    enum orderCategory {
      'businessCenterMain' = '2',
      'userCenterMain' = '1'
    }
    const params = {
      page: {
        current: unref(currentPage),
        size: unref(pageSize)
      },
      orderCategory: currentRoute.value.name ? orderCategory[currentRoute.value.name] : '',
      ...unref(searchParams)
    }
    if (queryConditions.value.length) {
      queryConditions.value.forEach((item) => {
        params[item.value] = item.name
      })
    }

    const res = await taskResourceApi(params)

    return {
      list: res.data || []
    }
  }
})
const { loading, dataList, currentPage, pageSize } = tableState
const { getList, refresh, getElTableExpose } = tableMethods

function headerCellStyle() {
  return { background: '#f5f5f5' }
}

const editVisble = ref(false)

const queryConditions = ref<{ [key in string]: any }[]>([])

const selectedRows = ref<any[]>([])

const handleSelectionChange = (val) => {
  selectedRows.value = val
}

const handleRowClick = async (row, column) => {
  const elTableExpose = await getElTableExpose()
  //判断是否选中
  if (!selectedRows.value.map((item) => item.id).includes(row.id)) {
    elTableExpose?.toggleRowSelection(row, true)
  } else {
    elTableExpose?.toggleRowSelection(row, false)
  }
}

const handelSelect = (value?: any) => {
  if (value) {
    queryConditions.value = value
  }
  getList()
}
function handleAdd() {
  operateType.value = 'add'
  editVisble.value = true
}
function handleEdit(id?: any) {
  rowId.value = id
  operateType.value = 'edit'
  editVisble.value = true
}
function handleDelete(row?: any) {
  let ids: any[] = []
  let names: any[] = []
  if (row) {
    ids = [row.id]
    names = [row.name]
  } else {
    selectedRows.value.forEach((item) => {
      const { id, name } = item
      ids.push(id)
      names.push(name)
    })
    // ids = getSelectionIds.value
    // names = selectedRows.value.map((item) => item.name)
  }
  ElMessageBox.confirm('您确定要删除所选任务 <b>' + names.join(', ') + '</b> 吗？', '删除任务', {
    confirmButtonText: '确定',
    cancelButtonText: t('common.cancel'),
    dangerouslyUseHTMLString: true,
    type: 'warning'
  })
    .then(async () => {
      const response = await deleteTaskApi({ id: ids[0] })
      if (response.code === SUCCESS_CODE) {
        ElMessage.success(t('common.success'))
        handelSelect()
      }
    })
    .catch(() => {})
}
</script>

<template>
  <div>
    <Table
      class="table-contain"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :header-cell-style="headerCellStyle"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      :show-action="true"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #customToolButtons>
        <ElSpace>
          <ElButton type="primary" @click="handleAdd">新增</ElButton>
        </ElSpace>
      </template>
    </Table>
    <!-- 添加编辑 -->
    <TaskDialog
      v-if="editVisble"
      v-model="editVisble"
      :type="operateType"
      :id="rowId"
      @handle-o-k="handelSelect"
    />
  </div>
</template>

<style scoped lang="less">
.form-item .el-form-item--large,
.el-form-item {
  margin-bottom: 0px;
}
::v-deep(.form-label-c .el-form-item__label) {
  color: #7f7f7f;
}
.table-contain {
  &::v-deep(.el-link__inner) {
    width: 100%;
    justify-content: normal;
  }
}
</style>
